import { BrowserWindow, app } from 'electron';
import { join } from 'path';
import { WindowOptions } from '../types';

/**
 * Boltron 增强型窗口类
 */
export class BoltronWindow {
  /**
   * Electron 原生窗口实例
   */
  private window: BrowserWindow;
  
  /**
   * 窗口名称
   */
  private name: string;
  
  /**
   * 窗口选项
   */
  private options: WindowOptions;
  
  /**
   * 默认窗口选项
   */
  private static DEFAULT_OPTIONS: Partial<WindowOptions> = {
    webPreferences: {
      contextIsolation: true,
      sandbox: true,
      webSecurity: true,
      nodeIntegration: false,
    },
    loadImmediately: true,
    autoShow: false,
  };

  /**
   * 创建 BoltronWindow 实例
   * @param name 窗口名称
   * @param options 窗口选项
   */
  constructor(name: string, options: WindowOptions) {
    this.name = name;
    
    // 合并默认选项
    this.options = {
      ...BoltronWindow.DEFAULT_OPTIONS,
      ...options,
      webPreferences: {
        ...BoltronWindow.DEFAULT_OPTIONS.webPreferences,
        ...options.webPreferences
      },
    };
    
    // 检查app是否准备就绪
    if (!app.isReady()) {
      throw new Error('Cannot create BrowserWindow before app is ready');
    }
    
    // 创建窗口
    this.window = new BrowserWindow(this.options);
    
    // 设置窗口 ID
    this.window.setTitle(`${this.name}-${this.window.id}`);
    
    // 注册窗口事件
    this.registerEvents();
    
    // 加载 URL
    if (this.options.loadImmediately) {
      this.loadURL(this.options.url);
    }
    
    // 自动显示
    if (this.options.autoShow) {
      this.show();
    }
  }

  /**
   * 注册窗口事件
   */
  private registerEvents(): void {
    // 窗口关闭时释放资源
    this.window.on('closed', () => {
      // @ts-ignore - 设置为 null 以便垃圾回收
      this.window = null;
    });
  }

  /**
   * 加载 URL
   * @param url 要加载的 URL
   */
  public loadURL(url: string): Promise<void> {
    return this.window.loadURL(url);
  }

  /**
   * 显示窗口
   */
  public show(): void {
    if (!this.window.isVisible()) {
      this.window.show();
    }
    this.window.focus();
  }

  /**
   * 隐藏窗口
   */
  public hide(): void {
    this.window.hide();
  }

  /**
   * 关闭窗口
   */
  public close(): void {
    if (!this.window.isDestroyed()) {
      this.window.close();
    }
  }

  /**
   * 最小化窗口
   */
  public minimize(): void {
    this.window.minimize();
  }

  /**
   * 最大化窗口
   */
  public maximize(): void {
    this.window.maximize();
  }

  /**
   * 还原窗口
   */
  public restore(): void {
    this.window.restore();
  }

  /**
   * 获取原生窗口实例
   */
  public getNativeWindow(): BrowserWindow {
    return this.window;
  }

  /**
   * 判断窗口是否已销毁
   */
  public isDestroyed(): boolean {
    return this.window.isDestroyed();
  }

  /**
   * 获取窗口 ID
   */
  public getId(): number {
    return this.window.id;
  }

  /**
   * 获取窗口名称
   */
  public getName(): string {
    return this.name;
  }
} 